﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Media;

namespace banolo12 {
	public static class TrackPlayer {
		private static int duration = 200;
		private static bool stopTrackLoop = false;
		private static int volume = 200;
		private static SoundPlayer SP = null;

		public static void SetVolume(int newVolume) {
			volume = newVolume;
		}

		public static void Beep(int Amplitude, int Frequency, int Duration) {
			try {
				if (!stopTrackLoop) {
					double A = ((Amplitude * 32768.0) / 1000.0) - 1.0;
					double DeltaFT = (2 * Math.PI * Frequency) / 44100.0;
					int Samples = (44100 * Duration) / 1000;
					int Bytes = Samples * 4;
					int[] Hdr = new int[] { 0x46464952, 0x24 + Bytes, 0x45564157, 0x20746d66, 0x10, 0x20001, 0xac44, 0x2b110, 0x100004, 0x61746164, Bytes };
					using (MemoryStream MS = new MemoryStream(0x24 + Bytes)) {
						using (BinaryWriter BW = new BinaryWriter(MS)) {
							int length = Hdr.Length - 1;
							for (int I = 0; I <= length; I++) {
								BW.Write(Hdr[I]);
							}
							int sample = Samples - 1;
							for (int T = 0; T <= sample; T++) {
								short Sample = (short)Math.Round((double)(A * Math.Sin(DeltaFT * T)));
								BW.Write(Sample);
								BW.Write(Sample);
							}
							BW.Flush();
							MS.Seek(0L, SeekOrigin.Begin);
							SP = new SoundPlayer(MS);

							SP.PlaySync();
						}
					}
				}
			} catch { }
		}

		public static void SetDuration(int newDuration) {
			duration = newDuration;
		}

		public static void StopTrackLoop() {
			stopTrackLoop = true;

			if (SP != null)
				SP.Stop();
		}

		public static void Play(uint[] track, bool loop = false) {
			stopTrackLoop = false;

			if (loop) {
				while (true)
					RealPlay(track);
			} else RealPlay(track);
		}

		public static void RealPlay(uint[] track) {
			foreach (uint frequency in track) {
				if (!stopTrackLoop) {
					if (frequency > 0)
						Beep(volume, (int)frequency, duration);
					else
						System.Threading.Thread.Sleep(duration);
				} else break;
			}
		}
	}
}
